﻿using System.Text.RegularExpressions;
using System.Web;

namespace CY_MVC.Core
{
    internal static class WebUrl
    {
        public readonly static Regex RegexUrl = string.IsNullOrEmpty(StaticConfig.UrlRewriteExtensions) ? new Regex(@"^/([\w\W]+?).(aspx|axd|ashx|html)$", RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase) : new Regex(@"^/([\w\W]+?).(" + StaticConfig.UrlRewriteExtensions + "|axd)$", RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);

        internal static string ControllerName(HttpContext p_Context)
        {
            var AbsolutePath = p_Context.Request.ApplicationPath == "/" ? p_Context.Request.Url.AbsolutePath : p_Context.Request.Url.AbsolutePath.Replace(p_Context.Request.ApplicationPath,  string.Empty);
            var match = RegexUrl.Match(AbsolutePath);
            var ControllerName = string.Empty;
            if (match.Success && match.Groups[1].Success)
            {
                ControllerName = match.Groups[1].Value.Replace("/", ".").ToLowerInvariant();
            }
            return ControllerName;
        }

        /// <summary>
        /// Converts a URL into one that is usable on the requesting client.
        /// </summary>
        /// <remarks>Converts ~ to the requesting application path.  Mimics the behavior of the 
        /// <b>Control.ResolveUrl()</b> method, which is often used by control developers.</remarks>
        /// <param name="p_AppPath">The application path.</param>
        /// <param name="p_Url">The URL, which might contain ~.</param>
        /// <returns>A resolved URL.  If the input parameter <b>url</b> contains ~, it is replaced with the
        /// value of the <b>appPath</b> parameter.</returns>
        internal static string ResolveUrl(string p_AppPath, string p_Url)
        {
            if (p_Url.Length == 0 || p_Url[0] != '~')
                return p_Url;		// there is no ~ in the first character position, just return the url
            if (p_Url.Length == 1)
                return p_AppPath;  // there is just the ~ in the URL, return the appPath
            if (p_Url[1] == '/' || p_Url[1] == '\\')
            {
                // url looks like ~/ or ~\
                if (p_AppPath.Length > 1)
                    return p_AppPath + "/" + p_Url.Substring(2);
                return "/" + p_Url.Substring(2);
            }
            // url looks like ~something
            if (p_AppPath.Length > 1)
                return p_AppPath + "/" + p_Url.Substring(1);
            return p_AppPath + p_Url.Substring(1);
        }
    }
}
